import 'package:auto_route/auto_route.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

/// 同步路由栈可返回状态到原生侧
class NativeRouteObserver extends AutoRouteObserver {
  static const _channel = MethodChannel('native_to_flutter_tuyavc');

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    debugPrint('119615→ Pushed: ${route.settings.name}');
    _updateNativePopState();
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    debugPrint('119615 POP: ${route.settings.name} at ${DateTime.now()}');
    _updateNativePopState();
  }

  void _updateNativePopState() {
    final location = appRouter.current.name;
    final bool isGuardedRoot =
        location.contains(DeviceShareListRoute.name) ||
        location.contains(FeedbackPostRoute.name) ||
        location.contains(ServiceRepairRoute.name) ||
        location.contains(TabRoute.name);
    _channel
        .invokeMethod('setCanPopInternal', {
          'canPop': isGuardedRoot ? false : appRouter.canPop(),
        })
        .catchError((e, st) {});
  }
}
